package com.ascent.server;

import com.ascent.bean.User;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.StringTokenizer;

public class UserDataAccessor extends DataAccessor{
    /**
     * 用户信息数据文件名
     */
    protected static final String USER_FILE_NAME = "database/user.db";
    @Override
    public void load() {
        try{
            userTable = new HashMap<String,User>();
            User userObject = null;
            StringTokenizer st = null;
            String line = "";
            line = "";
            String userName, password, authority;
            log("读取文件: " + USER_FILE_NAME + "...");
            BufferedReader inputFromFile2 = new BufferedReader(new FileReader(USER_FILE_NAME));
            while ((line = inputFromFile2.readLine()) != null) {

                st = new StringTokenizer(line, ",");

                userName = st.nextToken().trim();
                password = st.nextToken().trim();
                authority = st.nextToken().trim();
                userObject = new User(userName, password, Integer.parseInt(authority));

                if (!userTable.containsKey(userName)) {
                    userTable.put(userName, userObject);
                }
            }

            inputFromFile2.close();
            log("文件读取结束!");
            log("准备就绪!\n");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 新增用户数据
     * @param user
     */
    public void saveUser(User user) {
        log("读取文件: " + USER_FILE_NAME + "...");
        try {
            String userInfo = user.getUsername() + "," + user.getPassword() + "," + user.getAuthority();
            RandomAccessFile fos = new RandomAccessFile(USER_FILE_NAME, "rws");
            fos.seek(fos.length());
            fos.write((userInfo + "\n").getBytes());
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除用户接口
     * @param user
     */
    public void deleteUser(User user){
        String username = user.getUsername();
        log("删除： "+username+" 用户");
        try {
            // 读取文件内容
            Path path = Paths.get(USER_FILE_NAME);
            List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);

            //找到需要删除的用户名所在的行数
            int lineToDelete = -1;
            for (int i = 0;i < lines.size(); i++){
                String[] parts = lines.get(i).split(",");
                if (parts[0].equals(username)) {
                    lineToDelete = i;
                    break;
                }
            }
            // 如果找到了需要删除的用户名，则将其对应的行删除
            if (lineToDelete != -1) {
                lines.remove(lineToDelete);
            } else {
                log("未找到指定的用户！");
                return;
            }

            //将新的行写回文件中，覆盖原有内容
            Files.write(path, lines, StandardCharsets.UTF_8);
            log("已成功删除用户：" + username);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void updateUser(User user) {
        String username = user.getUsername();
        log("修改用户信息：" + username);
        try {
            // 读取文件内容
            Path path = Paths.get(USER_FILE_NAME);
            List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);

            //找到需要修改的用户名所在的行数，并将其替换为新的用户信息
            int lineToUpdate = -1;
            for (int i = 0;i < lines.size(); i++){
                String[] parts = lines.get(i).split(",");
                if (parts[0].equals(username)) {
                    lineToUpdate = i;
                    String userInfo = user.getUsername()+","+user.getPassword()+","+user.getAuthority();
                    lines.set(i, userInfo); //使用新的用户信息替换原有的行
                    break;
                }
            }
            // 如果找到了需要修改的用户名，则将其对应的行更新
            if (lineToUpdate != -1) {
                Files.write(path, lines, StandardCharsets.UTF_8);
                log("已成功更新用户：" + username);
            } else {
                log("未找到指定的用户！");
                return;
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 日志方法.
     */
    @Override
    protected void log(Object msg) {
        System.out.println("ProductDataAccessor类: " + msg);
    }

    public HashMap<String,User> getUsers() {
        this.load();
        return this.userTable;
    }
}
